<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useUserStore } from "../../store/modules/user";
import { getCaptcha, sendEmailVerifyCode } from "@/api/user";

const userStore = useUserStore();

// 使用计算属性跟踪是否处于登录模式
const isLogin = computed({
  get: () => userStore.authModalMode === "login",
  set: (value) => (userStore.authModalMode = value ? "login" : "register"),
});

// 更新表单数据，在登录时使用email字段而不是username
const formData = reactive({
  username: "", // 仅用于注册
  email: "", // 注册和登录都使用
  password: "",
  confirmPassword: "",
  captcha: "", // 图形验证码
  emailCode: "", // 邮箱验证码
});

const error = ref("");

// 图形验证码相关
const captchaImage = ref("");
const captchaKey = ref(""); // 存储验证码的key
const captchaLoading = ref(false);

// 邮箱验证码相关
const emailCodeSending = ref(false);
const emailCodeCountdown = ref(0);
const emailCodeTimer = ref(null);

// 生成图形验证码
const generateCaptcha = async () => {
  captchaLoading.value = true;

  try {
    // 调用API获取验证码
    const res = await getCaptcha();
    if (res && res.captchaImage) {
      captchaImage.value = res.captchaImage; // 直接使用返回的SVG字符串
      captchaKey.value = res.captchaKey; // 存储验证码key
    } else {
      error.value = "获取验证码失败，请刷新重试";
      console.error("验证码格式错误:", res);
    }
  } catch (err) {
    error.value = "获取验证码失败，请刷新重试";
    console.error("获取验证码出错:", err);
  } finally {
    captchaLoading.value = false;
  }
};

// 发送邮箱验证码
const sendEmailCode = async () => {
  // 验证邮箱格式
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!formData.email || !emailPattern.test(formData.email)) {
    error.value = "请输入有效的邮箱地址";
    return;
  }

  emailCodeSending.value = true;

  try {
    // 调用API发送验证码
    const result = await sendEmailVerifyCode({ email: formData.email });
    console.log("邮箱验证码发送结果:", result);

    // 开始倒计时
    emailCodeCountdown.value = 60;
    emailCodeTimer.value = setInterval(() => {
      emailCodeCountdown.value--;
      if (emailCodeCountdown.value <= 0) {
        clearInterval(emailCodeTimer.value);
      }
    }, 1000);
  } catch (err) {
    error.value = "发送验证码失败，请稍后重试";
    console.error("发送邮箱验证码失败:", err);
  } finally {
    emailCodeSending.value = false;
  }
};

// 验证邮箱格式
const validateEmail = () => {
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!formData.email) {
    error.value = "邮箱不能为空";
    return false;
  }
  if (!emailPattern.test(formData.email)) {
    error.value = "请输入有效的邮箱地址";
    return false;
  }
  return true;
};

const handleSubmit = async () => {
  error.value = "";

  // 通用验证 - 邮箱和密码 (对登录和注册都适用)
  if (!validateEmail()) {
    return;
  }

  if (!formData.password) {
    error.value = "密码不能为空";
    return;
  }

  if (isLogin.value) {
    // 登录模式验证
    if (!formData.captcha) {
      error.value = "请输入图形验证码";
      return;
    }
    // 调用登录功能 (使用email而不是username)
    const result = await userStore.handleLogin({
      email: formData.email, // 使用邮箱登录
      password: formData.password,
      captcha: formData.captcha,
      captchaKey: captchaKey.value, // 传递验证码key
    });

    if (result.success) {
      // 登录成功后重置表单
      resetForm();
    } else {
      error.value = result.error || "登录失败，请检查邮箱和密码";
      // 登录失败仅重置验证码，保留其他字段
      formData.captcha = "";
      generateCaptcha();
    }
  } else {
    // 注册模式的额外验证
    if (!formData.username) {
      error.value = "用户名不能为空";
      return;
    }

    if (formData.password !== formData.confirmPassword) {
      error.value = "两次输入的密码不一致";
      return;
    }

    if (!formData.emailCode) {
      error.value = "请输入邮箱验证码";
      return;
    }

    // 调用注册功能
    const result = await userStore.handleRegister({
      username: formData.username,
      password: formData.password,
      confirmPassword: formData.confirmPassword,
      email: formData.email,
      emailCode: formData.emailCode,
    });

    if (result.success) {
      if (result.requireLogin) {
        // 注册成功但需要手动登录
        isLogin.value = true;

        // 重置表单但保留邮箱
        resetForm(true);

        // 生成登录需要的验证码
        generateCaptcha();
      } else {
        // 注册成功并自动登录，完全重置表单
        resetForm();
      }
    } else {
      error.value = result.error || "注册失败，请稍后重试";
    }
    // 如果直接登录成功，userStore已经处理了关闭弹窗等操作
  }
};
// 重置表单数据的函数，可选是否保留邮箱
const resetForm = (keepEmail = false) => {
  // 保存邮箱（如果需要）
  const email = keepEmail ? formData.email : "";

  // 重置所有表单字段
  formData.username = "";
  formData.email = keepEmail ? email : "";
  formData.password = "";
  formData.confirmPassword = "";
  formData.captcha = "";
  formData.emailCode = "";
  error.value = "";

  // 清除邮箱验证码倒计时
  if (emailCodeTimer.value) {
    clearInterval(emailCodeTimer.value);
    emailCodeCountdown.value = 0;
  }
};

const toggleMode = () => {
  isLogin.value = !isLogin.value;
  // 重置表单
  resetForm();

  // 如果切换到登录模式，生成新的图形验证码
  if (isLogin.value) {
    generateCaptcha();
  }

  // 清除邮箱验证码倒计时
  if (emailCodeTimer.value) {
    clearInterval(emailCodeTimer.value);
    emailCodeCountdown.value = 0;
  }
};

// 在组件挂载时生成验证码（仅登录模式）
onMounted(() => {
  if (isLogin.value) {
    generateCaptcha();
  }
});
</script>

<template>
  <Teleport to="body">
    <div
      v-if="userStore.isAuthModalOpen"
      class="auth-modal-overlay"
      @click.self="userStore.closeAuthModal"
    >
      <div class="auth-modal">
        <!-- 顶部 -->
        <div class="auth-modal-header">
          <h2>{{ isLogin ? "登录" : "注册" }}</h2>
          <button class="close-button" @click="userStore.closeAuthModal">
            &times;
          </button>
        </div>
        <!-- TAB -->
        <div class="auth-modal-tabs">
          <button
            class="tab-button"
            :class="{ active: isLogin }"
            @click="isLogin = true"
          >
            登录
          </button>
          <button
            class="tab-button"
            :class="{ active: !isLogin }"
            @click="isLogin = false"
          >
            注册
          </button>
        </div>
        <!-- 表单 -->
        <div class="auth-modal-content">
          <form @submit.prevent="handleSubmit">
            <!-- error message -->
            <div v-if="error" class="error-message">
              {{ error }}
            </div>

            <!-- 注册模式下显示用户名字段 -->
            <div v-if="!isLogin" class="form-group">
              <label for="username">用户名</label>
              <input
                type="text"
                id="username"
                v-model="formData.username"
                required
                placeholder="请输入用户名"
              />
            </div>

            <!-- 邮箱字段 - 在登录和注册时都显示 -->
            <div class="form-group">
              <label for="email">电子邮箱</label>
              <div class="input-group">
                <input
                  type="email"
                  id="email"
                  v-model="formData.email"
                  required
                  placeholder="请输入邮箱地址"
                />
              </div>
            </div>

            <!-- 注册模式下的邮箱验证码 -->
            <div v-if="!isLogin" class="form-group">
              <label for="emailCode">邮箱验证码</label>
              <div class="input-group">
                <input
                  type="text"
                  id="emailCode"
                  v-model="formData.emailCode"
                  required
                  placeholder="请输入验证码"
                />
                <button
                  type="button"
                  class="email-code-button"
                  @click="sendEmailCode"
                  :disabled="emailCodeSending || emailCodeCountdown > 0"
                >
                  <span v-if="emailCodeCountdown > 0"
                    >{{ emailCodeCountdown }}秒后重新获取</span
                  >
                  <span v-else-if="emailCodeSending">发送中...</span>
                  <span v-else>获取验证码</span>
                </button>
              </div>
            </div>

            <div class="form-group">
              <label for="password">密码</label>
              <input
                type="password"
                id="password"
                v-model="formData.password"
                required
                placeholder="请输入密码"
              />
            </div>

            <div v-if="!isLogin" class="form-group">
              <label for="confirmPassword">确认密码</label>
              <input
                type="password"
                id="confirmPassword"
                v-model="formData.confirmPassword"
                required
                placeholder="请再次输入密码"
              />
            </div>

            <!-- 登录模式下的图形验证码 -->
            <div v-if="isLogin" class="form-group">
              <label for="captcha">图形验证码</label>
              <div class="input-group">
                <input
                  type="text"
                  id="captcha"
                  v-model="formData.captcha"
                  required
                  placeholder="请输入图中验证码"
                />
                <div class="captcha-image" @click="generateCaptcha">
                  <!-- 使用v-html来渲染SVG -->
                  <div
                    v-if="!captchaLoading && captchaImage"
                    v-html="captchaImage"
                    class="svg-container"
                    title="点击刷新"
                  ></div>
                  <div v-else class="captcha-loading">加载中...</div>
                </div>
              </div>
            </div>

            <!-- 登录注册按钮 -->
            <button type="submit" class="submit-button">
              {{ isLogin ? "登录" : "注册" }}
            </button>
          </form>

          <div class="auth-modal-footer">
            <p v-if="isLogin">
              还没有账号？
              <a href="#" @click.prevent="toggleMode">立即注册</a>
            </p>
            <p v-else>
              已有账号？
              <a href="#" @click.prevent="toggleMode">立即登录</a>
            </p>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
/* 样式部分保持不变 */
.auth-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.auth-modal {
  background-color: #ffffff;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  color: #333333;
}

/* 暗色模式适配 */
@media (prefers-color-scheme: dark) {
  .auth-modal {
    background-color: #1e1e1e;
    color: #e0e0e0;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
  }
}

.auth-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

@media (prefers-color-scheme: dark) {
  .auth-modal-header {
    border-bottom: 1px solid #333;
  }
}

.auth-modal-header h2 {
  margin: 0;
  font-size: 18px;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

@media (prefers-color-scheme: dark) {
  .close-button {
    color: #aaa;
  }
}

.auth-modal-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
}

@media (prefers-color-scheme: dark) {
  .auth-modal-tabs {
    border-bottom: 1px solid #333;
  }
}

.tab-button {
  flex: 1;
  padding: 12px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
  color: inherit;
}

.tab-button.active {
  background-color: #f5f5f5;
  font-weight: bold;
  border-bottom: 2px solid #3490dc;
}

@media (prefers-color-scheme: dark) {
  .tab-button.active {
    background-color: #2a2a2a;
    border-bottom: 2px solid #3490dc;
  }
}

.auth-modal-content {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  background-color: #ffffff;
  color: #333333;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-group input {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.svg-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.svg-container :deep(svg) {
  width: 100%;
  height: 100%;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-loading {
  font-size: 12px;
  color: #666;
}

.email-code-button {
  padding: 8px 12px;
  background-color: #3490dc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
  flex-shrink: 0;
  min-width: 130px;
  transition: background-color 0.2s;
}

.email-code-button:hover {
  background-color: #2779bd;
}

.email-code-button:disabled {
  background-color: #93c5fd;
  cursor: not-allowed;
}

@media (prefers-color-scheme: dark) {
  .form-group input {
    background-color: #2a2a2a;
    border: 1px solid #444;
    color: #e0e0e0;
  }

  .captcha-image {
    border-color: #444;
    background-color: #2a2a2a;
  }

  .captcha-loading {
    color: #aaa;
  }

  .email-code-button:disabled {
    background-color: #2c5282;
  }
}

.error-message {
  background-color: #fff5f5;
  color: #e53e3e;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
  border: 1px solid #feb2b2;
}

@media (prefers-color-scheme: dark) {
  .error-message {
    background-color: #3a1c1c;
    border-color: #742a2a;
    color: #f56565;
  }
}

.submit-button {
  width: 100%;
  padding: 10px;
  background-color: #3490dc;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
}

.submit-button:hover {
  background-color: #2779bd;
}

.auth-modal-footer {
  margin-top: 15px;
  text-align: center;
  font-size: 14px;
}

.auth-modal-footer a {
  color: #3490dc;
  text-decoration: none;
}

@media (prefers-color-scheme: dark) {
  .auth-modal-footer a {
    color: #63b3ed;
  }
}
</style>
